<?php

/**
 * This is the model class for table "{{files}}".
 *
 * The followings are the available columns in table '{{files}}':
 * @property integer $id
 * @property integer $senderId
 * @property integer $recipientId
 * @property string $filename
 * @property string $path
 * @property string $creationDate
 *
 * The followings are the available model relations:
 * @property Users $sender
 * @property Users $recipient
 */
class Files extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Files the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{files}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('senderId, recipientId, path, type, creationDate', 'required'),
			array('senderId, recipientId, fileSize, isNew', 'numerical', 'integerOnly'=>true),
			array('filename, path, mimeType', 'length', 'max'=>255),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, senderId, recipientId, filename, path, type, creationDate', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'sender' => array(self::BELONGS_TO, 'User', 'senderId'),
			'recipient' => array(self::BELONGS_TO, 'User', 'recipientId'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'senderId' => tt('Sender'),
			'recipientId' => tt('Recipient'),
			'filename' => tt('Filename'),
			'path' => tt('Path'),
			'creationDate' => tt('Creation Date'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		if (Yii::app()->user->id == 1)
		{
			$sql = "
				SELECT 
					f.*, 
					u2.username AS senderName, 
					u1.username AS recipientName
				FROM ".
					$this->tableName()." AS f
				LEFT JOIN 
					{{users}} AS u1
				ON 
					f.recipientId = u1.id
				LEFT JOIN 
					{{users}} AS u2
				ON 
					f.senderId = u2.id
				";
			$command = Yii::app()->db->createCommand($sql);
			$rawData = $command->queryAll();
		}
		else
		{
			$sql = "SELECT * FROM ".$this->tableName()." WHERE recipientId = :recipientId";
			$command = Yii::app()->db->createCommand($sql);
			$command->bindParam(":recipientId", Yii::app()->user->id, PDO::PARAM_INT);
			$rawData = $command->queryAll();
		}
			
		return new CArrayDataProvider($rawData, array(
			'pagination'=>array(
				'pageSize'=>param('adminPaginationPageSize', 20),
			),
		));
	}
        
    public function getUserFiles($userId, $onlyNew = false)
    {
	$files_list = array();
	if ($userId)
	{
	    $sql = "SELECT * FROM ".$this->tableName()." WHERE recipientId = :recipientId";
	    if ($onlyNew)
	    {
		$sql .= " AND isNew='1'";
	    }
		$sql .= ' ORDER BY creationDate DESC';
	    $command = Yii::app()->db->createCommand($sql);
	    $command->bindParam(":recipientId", $userId, PDO::PARAM_INT);
	    $rawData = $command->queryAll();
	    foreach($rawData as $k => $v){
		if ($v['type'] == 'file')
		{
		    $rawData[$k]['path'] =  $v['recipientId'].'/'.$v['filename']; 
		}
	    }
	    return $rawData;
	}
    }
		
		public function getNewFilesCount($userId)
		{
			$connection=Yii::app()->db;
			$sql = 'SELECT COUNT(*) as cnt FROM '.$this->tableName().' WHERE recipientId="'.$userId.'" AND isNew="1"';
			$command = $connection->createCommand($sql);
			$dataReader = $command->query();
			$count = 0;
			foreach($dataReader as $row) {
				if ($row['cnt'] > 0){
					$count = $row['cnt'];
					break;
				}
			}
			return $count;    
		}
		
		public function getLastFileDate($userId)
		{
			$connection=Yii::app()->db;
			$sql = 'SELECT creationDate FROM '.$this->tableName().' WHERE recipientId="'.$userId.'" ORDER BY creationDate DESC';
			$command = $connection->createCommand($sql);
			$dataReader = $command->query();
			$creationDate = 0;
			foreach($dataReader as $row)
			{
				$creationDate = $row['creationDate'];
				break;
			}
			return $creationDate;
		}
	
	public function isUserFileOwner($userId, $fileId)
	{
		$connection=Yii::app()->db;
		$sql = 'SELECT COUNT(*) as cnt FROM '.$this->tableName().' WHERE recipientId="'.$userId.'" AND id="'.$fileId.'"';
		$command = $connection->createCommand($sql);
		$dataReader = $command->query();
		$is_owner = 0;
		foreach($dataReader as $row)
		{
			if ($row['cnt'] > 0)
			{
				$is_owner = 1;
				break;
			}
		}
		return $is_owner;
	}
	
	public function markFileReaded($userId)
	{
		$connection=Yii::app()->db;
		$sql = 'UPDATE '.$this->tableName().' SET isNew="0" WHERE recipientId="'.$userId.'"';
		$command = $connection->createCommand($sql);
		$dataReader = $command->execute();

		return true;
	}
	
	private function _createAlias($fileName)
	{
		$ext = end(explode('.', $fileName));
		return time().".".$ext;
	}
	
	public function prepareFile($formModel)
	{
		$this->senderId = (!empty(Yii::app()->user->id)) ? Yii::app()->user->id : 2;
		$this->recipientId = $formModel->userId;
		$this->type = $formModel->type;
		$ts = mktime(date("H"), date("i"), date("s"), date("m"), date("d")+Yii::app()->params["uploadLifeTime"], date("Y"));
		$this->expirationDate = date("Y-m-d H:i:s", $ts);
		
		if (!empty($formModel->message))
		{
			$this->message = $formModel->message;
			$this->fileSize = mb_strlen($formModel->message);
		}
		
		if (!empty($formModel->filename))
		{
			$this->filename = $formModel->filename->getName();
			$this->mimeType = $formModel->filename->getType();
			$this->fileSize = $formModel->filename->getSize();
			$this->path = $this->_createAlias($this->filename);

			if (!file_exists(Yii::getPathOfAlias('webroot.uploads').DIRECTORY_SEPARATOR.$this->recipientId))
				mkdir(Yii::getPathOfAlias('webroot.uploads').DIRECTORY_SEPARATOR.$this->recipientId, 0777);
			
			$formModel->filename->saveAs(Yii::getPathOfAlias('webroot.uploads').DIRECTORY_SEPARATOR.$this->recipientId.DIRECTORY_SEPARATOR.$this->path);
		}
	}
	
	public function afterDelete()
	{
		$filename = Yii::getPathOfAlias('webroot.uploads').DIRECTORY_SEPARATOR.$this->recipientId.DIRECTORY_SEPARATOR.$this->path;
		if (!empty($this->path) && file_exists($filename))
			unlink($filename);
		parent::afterDelete();
	}
	
	
	public function deleteExpired()
	{
		$command = Yii::app()->db->createCommand("SELECT recipientId, path, type FROM {{files}} WHERE expirationDate < NOW()");
		$rawData = $command->queryAll();
		
		foreach ($rawData as $data)
		{
			if (!empty($data["path"]))
				unlink(Yii::getPathOfAlias('webroot.uploads').DIRECTORY_SEPARATOR.$data["recipientId"].DIRECTORY_SEPARATOR.$data["path"]);
		}
		
		$command = Yii::app()->db->createCommand("DELETE FROM {{files}} WHERE expirationDate < NOW()");
		$command->execute();
	}
}